﻿using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public static class TextureGenerator {
    #region 变量

    #endregion

    #region 自定义函数
    /// <summary>
    /// 生成彩色图
    /// </summary>
    /// <param name="colorMap">输入的颜色数组</param>
    /// <param name="width">图宽</param>
    /// <param name="height">图高</param>
    /// <returns></returns>
    public static Texture2D TextureFromColorMap (Color[] colorMap, int width, int height) {
        Texture2D texture = new Texture2D (width, height);
        // 过滤模式设置成点模式，获得清晰的像素
        texture.filterMode = FilterMode.Point;
        // 设置循环模式为固定，防止边缘重复
        texture.wrapMode = TextureWrapMode.Clamp;
        texture.SetPixels (colorMap);
        texture.Apply ();
        return texture;
    }

    /// <summary>
    ///  生成黑白高度图
    /// </summary>
    /// <param name="heightMap">输入的噪声图</param>
    /// <returns></returns>
    public static Texture2D TextureFromHeightMap (float[, ] heightMap) {
        // 获取噪声图的长和宽
        int width = heightMap.GetLength (0);
        int height = heightMap.GetLength (1);

        // 设置颜色
        Color[] colorMap = new Color[width * height];
        for (int y = 0; y < height; y++) {
            for (int x = 0; x < width; x++) {
                // 给颜色数组赋值，通过噪声图计算颜色
                colorMap[y * width + x] = Color.Lerp (Color.black, Color.white, heightMap[x, y]);
            }
        }
        return TextureFromColorMap (colorMap, width, height);
    }
    #endregion
}